import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { ElMessage, ElMessageBox } from "element-plus";
import "element-plus/es/components/message/style/css"; // 按需引入ElMessage样式失败，手动引入
import "element-plus/es/components/message-box/style/css";
import router from "@/router/index";
//pinia
// import pinia from '@/store/index'  // createPinia()
import { useUserStore } from "@/store/user";
const userStore = useUserStore();

const service = axios.create();

// Request interceptors
service.interceptors.request.use(
  // (config: AxiosRequestConfig) => {
  (config: any) => {
    // 判断是否存在token,如果存在将每个页面header添加token
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    return config;
  },
  (error: any) => {
    Promise.reject(error);
  }
);

// Response interceptors
service.interceptors.response.use(
  // async (response: AxiosResponse) => {
  async (response: any) => {
    // 对响应数据做点什么
    if (response.status === 200 || response.status === 0) { //成功状态码200
      //! do something
      return response
    } else {
      return Promise.reject(response)
    }
  },
  (error: any) => {
    const status = error.response.data.status
    const message = error.response.data.message
    // 对响应错误做点什么
    if (status) {
      switch (status) {
        //未登录或登录过期,跳转到登录页并携带当前页路径，登录成功后跳转
        case 401:
          ElMessage({
            showClose: true,
            message: `${message}`,
            type: 'error',
          })
          // 清除本地持久化的token和username
          localStorage.removeItem('token')
          localStorage.removeItem('username')
          localStorage.removeItem('userinfo')
          userStore.clearToken();
          userStore.clearUserName();
          userStore.clearUserInfo();
          // setTimeout(() => {
          //   router.replace({
          //     path: '/login',
          //   })
          // }, 500)
          break;
        //请求不存在		
        case 404:
          ElMessage({
            showClose: true,
            message: `${message}`,
            type: 'error',
          })
          break;
        //其他错误，提示错误
        default:
          ElMessage({
            showClose: true,
            message: `${message}`,
            type: 'error',
          })
      }
    }
    return Promise.reject(error.response);
  }
);

export default service;